package com.treasure.service.tally.service.impl;

import com.treasure.service.commons.lang.util.IdCreater;
import com.treasure.service.domain.TAccountChangeLog;
import com.treasure.service.domain.TUserAccount;
import com.treasure.service.mapper.TAccountChangeLogMapper;
import com.treasure.service.mapper.TUserAccountMapper;
import com.treasure.service.tally.service.TallyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @Description:    用户个人账户维护
* @Author:         panxinwen
* @CreateDate:     2018/11/12 22:00
* @Version:        1.0
*/
@Service
public class TallyServiceImpl implements TallyService {

    @Autowired
    private TUserAccountMapper  tUserAccountMapper;

    @Autowired
    private TAccountChangeLogMapper tAccountChangeLogMapper;

    @Override
    public Integer tally(Integer type, Long amount, Long userId, Long orderId) {

        TUserAccount tUserAccount = new TUserAccount();
        tUserAccount.setUserId(userId);
        tUserAccount = tUserAccountMapper.selectOne(tUserAccount);

        //Todo 资金变动记录
        TAccountChangeLog tAccountChangeLog = new TAccountChangeLog();
        tAccountChangeLog.setAccountType(1);
        tAccountChangeLog.setAddTime(new Date());
        tAccountChangeLog.setAfterChangeAmount(tUserAccount.getTotalBalance()+amount);
        tAccountChangeLog.setBeforeChangeAmount(tUserAccount.getTotalBalance());
        tAccountChangeLog.setBizId(orderId);
        tAccountChangeLog.setChangeAmount(amount);
        tAccountChangeLog.setCouponAmount(0l);
        tAccountChangeLog.setId(IdCreater.getLongId());
        tAccountChangeLog.setSubType(type);
        tAccountChangeLog.setUserId(userId);

        tUserAccount.setTotalAssets(tUserAccount.getTotalAssets()+amount);
        tUserAccount.setTotalBalance(tUserAccount.getTotalBalance()+amount);
        tUserAccountMapper.updateByPrimaryKeySelective(tUserAccount);

        return tAccountChangeLogMapper.insert(tAccountChangeLog);

    }
}
